import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;

public final class InputController implements KeyListener {
	private boolean keyPressed;
	private boolean keyReleased; 			//cleared every frame.
	private static InputController im = null;

	protected InputController() {
		keyPressed = false;
		keyReleased = false;
	}

	public static InputController getInstance() {
		if(im == null)	
			im = new InputController();
		return im;
	}
	
	public void keyPressed(KeyEvent e){
		if(!keyPressed){
			try {
				handleInputPressed(e.getKeyCode());
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		keyPressed = true;
		keyReleased = false;
	}

	public void keyReleased(KeyEvent e) {
		if(!keyReleased){
			try {
				handleInputReleased(e.getKeyCode());
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		keyPressed = false;
		keyReleased = true;
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	public void handleInputPressed(int keyCode) throws IOException, Exception{
		switch(keyCode){
			case 96:
				Telnet.getTelnet().getWrite().sendMove(Telnet.Direction.FLOAT.direction);
				break;
			case 99:
				Telnet.getTelnet().getWrite().sendMove(Telnet.Direction.RIGHT.direction);
				break;
			case 97:
				Telnet.getTelnet().getWrite().sendMove(Telnet.Direction.LEFT.direction);
				break;
			case 101:
				Telnet.getTelnet().getWrite().sendMove(Telnet.Direction.UP.direction);
				break;
			case 98:
				Telnet.getTelnet().getWrite().sendMove(Telnet.Direction.DOWN.direction);
				break;
			case 100:
				Telnet.getTelnet().getWrite().sendMove(Telnet.Direction.RLEFT.direction);
				break;
			case 102:
				Telnet.getTelnet().getWrite().sendMove(Telnet.Direction.RRIGHT.direction);
				break;
			case 65:
				Telnet.getTelnet().ping();
				break;
			case 80:
				Telnet.getTelnet().getWrite().sendPing();
				break;
			default:
				System.out.println("not used: " + keyCode);
				break;
		}
	}
	
	public void handleInputReleased(int keyCode) throws IOException, Exception{
		switch(keyCode){
			case 96:
				System.out.println("already floating");
				break;
			case 97:
			case 98:
			case 99:
			case 100:
			case 101:
			case 102:
				Telnet.getTelnet().getWrite().sendMove(Telnet.Direction.FLOAT.direction);
				break;
			default:
				System.out.println("not used: " + keyCode);
				break;
		}
	}
	
}
